package com.mcflies.commons.commons;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;

import com.mcflies.commons.bean.AreaBean;

/**
 * 
 * BaseDataLoadListener.java
 * 
 * @describe：基础数据加载监听器
 * @Copyright(c) 2012-2024 Study,mcfly
 * @author mcfly_jun
 */
public class BaseDataLoadListener implements ServletContextListener {
	private Logger log = Logger.getLogger(BaseDataLoadListener.class);

	@Override
	public void contextDestroyed(ServletContextEvent event) {
		ServletContext context = event.getServletContext();
		context.removeAttribute(CommonsConstantKey.BaseDataLoadListenerConstant.BaseDataLoadListenerBank);
		context.removeAttribute(CommonsConstantKey.BaseDataLoadListenerConstant.BaseDataLoadListenerProvince);
		context.removeAttribute(CommonsConstantKey.BaseDataLoadListenerConstant.BaseDataLoadListenerProvinceRegionMap);
	}

	@Override
	public void contextInitialized(ServletContextEvent event) {
		ServletContext context = event.getServletContext();
		try {
			loadBankInfo(context);
			loadAreaInfo(context);
			loadLeftMenuTree(context);
		} catch (Exception e) {
			log.error("BaseDataLoadListener::contextInitialized~~~~发生&&&&" + e.getMessage());
		}
	}

	private void loadBankInfo(ServletContext context) {
		log.info("BaseDataLoadListener::loadBankInfo~~~~开始");
		Map<String, Object> bankMap = CommonFunction.getAllBankInfo();
		context.setAttribute(CommonsConstantKey.BaseDataLoadListenerConstant.BaseDataLoadListenerBank, bankMap);
		log.info("BaseDataLoadListener::loadBankInfo~~~~结束");
	}

	private void loadAreaInfo(ServletContext context) {
		log.info("BaseDataLoadListener::loadAreaInfo~~~~开始");
		AreaBean areaBean = CommonFunction.getAreaInfo();
		if (null != areaBean) {
			context.setAttribute(CommonsConstantKey.BaseDataLoadListenerConstant.BaseDataLoadListenerProvince, areaBean
					.getProvinceMap());
			context.setAttribute(CommonsConstantKey.BaseDataLoadListenerConstant.BaseDataLoadListenerProvinceRegionMap,
					areaBean.getProvinceRegionMap());
		}
		log.info("BaseDataLoadListener::loadAreaInfo~~~~结束");
	}

	private void loadLeftMenuTree(ServletContext context) {
		log.info("BaseDataLoadListener::loadLeftMenu~~~~开始");
		try {
			JSONArray leftMenuTreeArr = CommonFunction.getLeftMenuTree();
			context.setAttribute(
					CommonsConstantKey.BaseDataLoadListenerConstant.BaseDataLoadListenerLEFTMENUTREEJSONARRAY,
					leftMenuTreeArr);
		} catch (Exception e) {
			log.info("在[" + BaseDataLoadListener.class.getName() + "]执行方法(loadLeftMenuTree)出现：：" + e.getMessage()
					+ "异常");
		}
		log.info("BaseDataLoadListener::loadLeftMenu~~~~结束");
	}

}
